// notification.js
(function() {
    var NotificationManager = {
        socket: null,
        userId: null,
        notificationContainer: null,

        init: function(userId) {
            console.log('初始化通知管理器');
            this.userId = userId;

            // 确保DOM加载完成后再初始化
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    this.createNotificationContainer();
                    this.connect();
                }.bind(this));
            } else {
                this.createNotificationContainer();
                this.connect();
            }
        },

        connect: function() {
            if (!this.userId) {
                console.warn('用户ID未设置，无法建立WebSocket连接');
                return;
            }

            var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            var wsUrl = protocol + '//' + window.location.host +
                '/blog/websocket/notification/' + this.userId;

            try {
                this.socket = new WebSocket(wsUrl);

                this.socket.onopen = function(event) {
                    console.log('WebSocket connected');
                };

                this.socket.onmessage = function(event) {
                    console.log('receive webSocket message:', event.data)
                    var message = JSON.parse(event.data);
                    this.showNotification(message);
                }.bind(this);

                this.socket.onclose = function(event) {
                    console.log('WebSocket closed');
                    // 可以选择性地重新连接
                    setTimeout(this.connect.bind(this), 5000);
                }.bind(this);

                this.socket.onerror = function(error) {
                    console.error('WebSocket error:', error);
                };
            } catch (e) {
                console.error('WebSocket连接失败:', e);
            }
        },

        createNotificationContainer: function() {
            // 确保document.body存在
            if (!document.body) {
                console.error('document.body不存在，无法创建通知容器');
                return;
            }

            // 检查是否已经存在通知容器
            this.notificationContainer = document.getElementById('notification-container');
            if (!this.notificationContainer) {
                // 创建通知容器
                this.notificationContainer = document.createElement('div');
                this.notificationContainer.id = 'notification-container';
                this.notificationContainer.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    z-index: 10000;
                    width: 300px;
                `;
                document.body.appendChild(this.notificationContainer);
            }
        },

        showNotification: function(message) {
            // 确保通知容器存在
            if (!this.notificationContainer) {
                this.createNotificationContainer();
                if (!this.notificationContainer) {
                    console.error('无法创建通知容器');
                    return;
                }
            }

            // 创建通知元素
            var notification = document.createElement('div');
            notification.className = 'notification-item';
            notification.style.cssText = `
                background: #fff;
                border-left: 4px solid #4CAF50;
                box-shadow: 0 2px 8px rgba(0,0,0,0.15);
                margin-bottom: 10px;
                padding: 15px;
                border-radius: 4px;
                cursor: pointer;
                transition: all 0.3s ease;
                opacity: 0;
                transform: translateX(100%);
            `;

            var title = document.createElement('div');
            title.style.cssText = `
                font-weight: bold;
                color: #333;
                margin-bottom: 5px;
            `;
            title.textContent = message.title || '通知';

            var content = document.createElement('div');
            content.style.cssText = `
                color: #666;
                font-size: 14px;
            `;
            content.textContent = message.content || '';

            notification.appendChild(title);
            notification.appendChild(content);

            // 如果有文章ID，添加点击跳转功能
            if (message.articleId) {
                notification.onclick = function() {
                    window.open('/article.jsp?id=' + message.articleId, '_blank');
                };
            }

            this.notificationContainer.appendChild(notification);

            // 动画显示
            setTimeout(function() {
                notification.style.opacity = '1';
                notification.style.transform = 'translateX(0)';
            }, 10);

            // 3秒后淡出
            setTimeout(function() {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';

                // 动画结束后移除元素
                setTimeout(function() {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
    };

    // 暴露到全局对象
    window.NotificationManager = NotificationManager;
})();
